package com.example.demo.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.CustomException;
import com.example.demo.common.R;
import com.example.demo.dto.SetmealDto;
import com.example.demo.entity.Category;
import com.example.demo.entity.Setmeal;
import com.example.demo.entity.SetmealDish;
import com.example.demo.service.CategoryService;
import com.example.demo.service.SetmealDishService;
import com.example.demo.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author guo
 * @since 2022-04-18
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    /**
     * 新增套餐方法
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);
        //构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotBlank(name), Setmeal::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //只查isDelete=0的数据
        queryWrapper.eq(Setmeal::getIsDeleted, 0);

        //执行查询
        setmealService.page(pageInfo, queryWrapper);
        //对象拷贝,分页数据
        BeanUtil.copyProperties(pageInfo, setmealDtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        //两个数据的集合
        List<SetmealDto> list = records.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();//此时其他属性除categoryName为null，需拷贝
            BeanUtil.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();//拿到分类id
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            setmealDto.setCategoryName(categoryName);
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }
    /**
     * 批量删除套餐，删除单个套餐
     *
     * @param
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }
    /**
     * 根据分类id查询套餐信息
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        Long categoryId = setmeal.getCategoryId();
        if (org.springframework.util.StringUtils.isEmpty(categoryId)) {
            throw new CustomException("系统错误！！");
        }
        if (org.springframework.util.StringUtils.isEmpty(setmeal.getStatus())) {
            throw new CustomException("系统错误");
        }

        QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.eq("status", 1);

        List<Setmeal> setmeals = setmealService.list(wrapper);
        return R.success(setmeals);
    }
    /**
     * （可批量）1启售  0停售
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") int status, @RequestParam List<Long> ids) {
        ids.stream().forEach((id) -> {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        });
        return R.success("操作成功");
    }
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateSetmeal(setmealDto);
        return R.success("修改成功");
    }
    //数据回显
    @GetMapping("{id}")
    public R<SetmealDto> getById(@PathVariable("id") Long id) {
        if (id == null) {
            throw new CustomException("系统错误！");
        }
        Setmeal setmeal = setmealService.getById(id);

        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();
        wrapper.eq("setmeal_id", id);

        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);

        Category category = categoryService.getById(setmeal.getCategoryId());

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        setmealDto.setSetmealDishes(setmealDishes);
        setmealDto.setCategoryName(category.getName());
        return R.success(setmealDto);
    }
}
